package com.wennimei.service;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.wennimei.dao.JokeDAO;
import com.wennimei.util.MemcachedUtil;
import com.wennimei.util.Switcher;

public class JokeService {

    private static Logger log = Logger.getLogger(JokeService.class);

    @Autowired
    private JokeDAO jokeDAO;

    @Autowired
    private Switcher switcher;

    private static HttpClient client = new HttpClient();

    private AtomicBoolean running = new AtomicBoolean(false);

    private final long maxExpire = 1000 * 60 * 30;

    void init() {

        if (!switcher.isOpen())
            return;

        if (running.get())
            return;
        long start = System.currentTimeMillis();
        try {
            running.set(true);
            Integer maxId = jokeDAO.getMaxId();
            maxId = (null == maxId) ? 0 : maxId;
            while (true) {
                long expire = System.currentTimeMillis() - start;
                if (expire >= maxExpire)
                    return;

                log.info("start crawl " + maxId);
                try {
                    GetMethod get = new GetMethod(
                            String.format(
                                    "http://joke.3g.cn/ipnewscontent.php?nid=%s",
                                    maxId));
                    client.executeMethod(get);
                    String html = new String(get.getResponseBody(), "utf-8");
                    if (!html.contains("content_text"))
                        continue;
                    html = html.trim().replaceAll("[\\s]", "");
                    Pattern pattern = Pattern
                            .compile(".*<!--新闻具体内容\\)-->(.*)<!--新闻内容分页-->.*");
                    Matcher matcher = pattern.matcher(html);
                    String clean = null;
                    while (matcher.find()) {
                        clean = matcher.group(1);
                    }
                    if (null == clean)
                        continue;

                    clean = clean.replaceAll("<br/>", "").replaceAll("\\t", "")
                            .replaceAll("\\r", "").replaceAll("</div>", "")
                            .trim();
                    if (clean.matches(".*<[^>]+>.*"))
                        continue;
                    jokeDAO.insertJoke(maxId, clean);
                    log.info(clean);
                } catch (Exception e) {
                    log.error("crawl joke error", e);
                    continue;
                } finally {
                    maxId++;
                }
            }
        } finally {
            running.set(false);
        }

    }

    public String get() {
        Integer sum = (Integer) MemcachedUtil.getInstance().get("joke_sum");
        if (null == sum) {
            sum = this.jokeDAO.sum();
            MemcachedUtil.getInstance().set("joke_sum", 60 * 60 * 24, sum);
        }

        int rand = (int) (Math.random() * sum);

        String joke = this.jokeDAO.getJoke(rand);
        if (null != joke && joke.length() > 600)
            joke = joke.substring(0, 600);
        return joke;
    }
}
